package com.soriya.nestlive.component

import android.app.Activity
import android.util.Log
import android.view.View
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.VideoAllCallBack
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.soriya.nestlive.R
import com.soriya.nestlive.constant.ServerConstant
import tv.danmaku.ijk.media.player.IjkMediaPlayer
import java.io.File

@Composable
fun CustomImage(
    modifier: Modifier = Modifier,
    url: String,
    contentDescription: String,
    shape: Shape = MaterialTheme.shapes.large,
    scale: ContentScale = ContentScale.Crop,
    error: Painter = painterResource(id = R.mipmap.failed_pic)
) {
    if (url.isEmpty()) return

    val imageUrl = if (url.startsWith("http")) url else ServerConstant.IMAGE_URL + url
    AsyncImage(
        model = ImageRequest.Builder(LocalContext.current)
            .data(data = imageUrl)
            .transformations()
            .build(),
        contentDescription = contentDescription,
        contentScale = scale,
        error = error,
        modifier = modifier
            .clip(shape)
    )
}

@Composable
fun CustomImage(
    modifier: Modifier = Modifier,
    file: File,
    contentDescription: String,
    shape: Shape = MaterialTheme.shapes.large,
    scale: ContentScale = ContentScale.Crop,
    error: Painter = painterResource(id = R.mipmap.failed_pic)
) {
    AsyncImage(
        model = ImageRequest.Builder(LocalContext.current)
            .data(data = file)
            .build(),
        contentDescription = contentDescription,
        contentScale = scale,
        error = error,
        modifier = modifier
            .clip(shape)
    )
}

@Composable
fun GsyPlayer(
    url: String,
    optionBuilder: GSYVideoOptionBuilder,
    modifier: Modifier = Modifier
) {
    if (url.isEmpty()) return

    lateinit var videoView: StandardGSYVideoPlayer
    lateinit var orientationUtils: OrientationUtils

    val context = LocalContext.current as Activity

    val videoUrl = if (url.startsWith("http", true) || url.startsWith("rtmp", true)) url else ServerConstant.VOD_URL + url

    AndroidView(
        factory = { _ ->
            IjkPlayerManager.setLogLevel(IjkMediaPlayer.IJK_LOG_SILENT)

            videoView = StandardGSYVideoPlayer(context)

//            videoView.setUp(path, true, "测试视频")
            videoView.titleTextView.visibility = View.GONE
            videoView.backButton.visibility = View.GONE

            orientationUtils = OrientationUtils(context, videoView)
            orientationUtils.isEnable = false
            videoView.fullscreenButton.setOnClickListener {
                if (orientationUtils.isLand != 1) {
                    orientationUtils.resolveByClick()
                }
                videoView.startWindowFullscreen(context, true, true)
            }

            optionBuilder
                .setUrl(videoUrl)
                .setVideoAllCallBack(object : VideoAllCallBack {
                    override fun onStartPrepared(url: String?, vararg objects: Any?) {}

                    override fun onPrepared(url: String?, vararg objects: Any?) {
                        orientationUtils.isEnable = true
                    }

                    override fun onClickStartIcon(url: String?, vararg objects: Any?) {}

                    override fun onClickStartError(url: String?, vararg objects: Any?) {}

                    override fun onClickStop(url: String?, vararg objects: Any?) {}

                    override fun onClickStopFullscreen(url: String?, vararg objects: Any?) {}

                    override fun onClickResume(url: String?, vararg objects: Any?) {}

                    override fun onClickResumeFullscreen(url: String?, vararg objects: Any?) { }

                    override fun onClickSeekbar(url: String?, vararg objects: Any?) {}

                    override fun onClickSeekbarFullscreen(url: String?, vararg objects: Any?) { }

                    override fun onAutoComplete(url: String?, vararg objects: Any?) {}

                    override fun onComplete(url: String?, vararg objects: Any?) {}

                    override fun onEnterFullscreen(url: String?, vararg objects: Any?) {}

                    override fun onQuitFullscreen(url: String?, vararg objects: Any?) {}

                    override fun onQuitSmallWidget(url: String?, vararg objects: Any?) {}

                    override fun onEnterSmallWidget(url: String?, vararg objects: Any?) {}

                    override fun onTouchScreenSeekVolume(url: String?, vararg objects: Any?) {}

                    override fun onTouchScreenSeekPosition(url: String?, vararg objects: Any?) {}

                    override fun onTouchScreenSeekLight(url: String?, vararg objects: Any?) {}

                    override fun onPlayError(url: String?, vararg objects: Any?) {}

                    override fun onClickStartThumb(url: String?, vararg objects: Any?) {}

                    override fun onClickBlank(url: String?, vararg objects: Any?) {}

                    override fun onClickBlankFullscreen(url: String?, vararg objects: Any?) {}
                })
                .build(videoView)

            videoView.startPlayLogic()

            videoView
        },
        modifier = modifier
    )


    val lifecycle = LocalLifecycleOwner.current.lifecycle

    DisposableEffect(Unit) {

        val lifecycleEventObserver = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_CREATE -> {
                    Log.i("SoRiya", "Created...")
                }
                Lifecycle.Event.ON_RESUME -> {
//                    ksyTextureView?.runInForeground()
                }
                Lifecycle.Event.ON_PAUSE -> {
//                    ksyTextureView?.runInBackground(false) // true后台音频继续播放 false停止所有播放
                }
                else -> {}
            }
        }

        lifecycle.addObserver(lifecycleEventObserver)

        onDispose {
            videoView.release()
            lifecycle.removeObserver(lifecycleEventObserver)
        }
    }
}
